package com.ophiux.cs.im.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

import com.ophiux.cs.application.chat.dto.SendCSMessageRequest;
import com.ophiux.cs.application.chat.dto.SendCSMessageResponse;
import com.ophiux.cs.application.chat.service.ISendCSMessageAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.utils.parser.json.JsonUtils;

/**
 * 即时通信控制器
 * @author chenh
 *
 */
@RestController
public class WebSocketController {

	//通过simpMessagingTemplate向浏览器发送消息
	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;
	
	@Autowired
	private ISendCSMessageAppService sendCSMessageAppService;
		
	@MessageMapping("/send")
	//@SendToUser("/getResponse")
    //在springmvc中,可以直接在参数中获得principal,pinciple中包含当前用户信息
	public Result handleChat(String message) {
		//向用户发送消息,第一个参数:接收消息的用户,第二个参数:浏览器订阅地址,第三个参数:消息
		Result<SendCSMessageResponse> result = null;
		try {
			SendCSMessageRequest msgReq = JsonUtils.getIstance().toEntity(message, SendCSMessageRequest.class); 
			
			String toUser = msgReq.getTO_USER();
			String content = msgReq.getCONTENT();
			String fromUser = msgReq.getFROM_USER();
			//执行消息存储
			result = sendCSMessageAppService.sendConMessage(msgReq);
			//消息实时推送
			/*simpMessagingTemplate.convertAndSendToUser(toUser, 
		                "/message/"+fromUser, content);*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
